<?php 
if( !defined('CORE_PATH')) die('Access Denied');

kan_import('ExportManager.php');

class ThemeManager extends Manager {
	
    protected $models = array("Theme","ThemeCSS");
	
	public function __construct() {
		parent::__construct('site_themes');
		$this->setItemClassName('Theme');
	}

    /**
     *
     * @param mixed $id array or int of data
     * @return Theme
     */
    public function getTheme($id) {
        $theme = $this->getItem($id);
        
        return $theme;
    }

    /**
     *
     * @param int $start
     * @param int $limit
     * @param array $options
     * @return Theme[]
     */
    public function getThemes($start = 0, $limit = NULL, $options = NULL) {
        return $this->getItems($start, $limit, $options);
    }
	
    /**
     * 
     * @param int $theme_id 
     */
	public function exportTheme($theme_id) {
		if( !defined("IN_CMS") || !IN_CMS ) {
            trigger_error("This function should only be run from the CMS interface");
            return;
        }
		
        $theme = new Theme($theme_id);
        $styleSheetObjs = $theme->getThemeStyleSheets();
        $styleSheets = array();
        
        foreach($styleSheetObjs as $sheet) {
            $styleSheets[] = $sheet->getDataArray();
        }
        
		$data = array(
			"theme_data" => $theme->getDataArray(),
			"stylesheets" => $styleSheets
		);
        
        $exporter = new ExportManager();
		$exporter->zipAndDownloadFolder( kan_fix_path($theme->getData('ThemeFolder')), $data );
	}
	
	public function exportStyle($css_id) {
		
		$themeCSS = new ThemeCSS($css_id);
		
		$cssFolder = $themeCSS->getData('CSSFolder') != '' ? $themeCSS->getData('CSSFolder') : dirname($themeCSS->getData('CSSURL'));

        $exporter = new ExportManager();
		$exporter->zipAndDownloadFolder( kan_fix_path($cssFolder), $css_data );		
	}
	
	public function uploadAndInstallCSS($themeFolder, $insertid) {
	   // get a reference to the db connection
	   global $config;
	
	   foreach ($_FILES as $key => $value) {
		  if ($_FILES[$key]["error"] == 0) {
			 // get the name of the file uploaded
			 $fileName = $_FILES[$key]["name"];
			 $destFolder = $themeFolder . "css/";
	
			 // if the file is not a zip file, then continue to the next file
			 if( strpos($fileName, ".zip") == -1 || strpos($fileName, ".zip") == "" || strpos($fileName, ".zip") == NULL ) {
				continue;
			 }
	
			 $destZipFile = $destFolder . $_FILES[$key]["name"];
	
			 // move the file to the CSS folder
			 move_uploaded_file($_FILES[$key]["tmp_name"], $destZipFile );
	
			 $cssFolderName = substr($fileName, 0, strpos($fileName,".") );
	
			 // create object
			 $zip = new ZipArchive() ;
	
			 // open archive
			 if ($zip->open( $destZipFile ) !== TRUE) {
				die ('Could not open archive');
			 } 
	
			 // extract contents to destination directory
			 $zip->extractTo($destFolder);
	
			 // close archive
			 $zip->close();
	
			 unlink( $destZipFile );
	
			 // if we managed to upzip successfully, then we must update the db record with the
			 // new path
			 $sheetFolder = $destFolder . $cssFolderName . "/";
			 $sheetPath = $sheetFolder . $cssFolderName . ".css" ;
	
             $themeCSS = new ThemeCSS(array(
                 'id' => $insertid,
                 'CSSFolder' => $sheetFolder,
                 'CSSURL' => $sheetPath,
             ));
             $themeCSS->save();
		  }
	   }
	}
	
	public function importTheme() {
	   // get a reference to the db connection
	
	   foreach ($_FILES as $key => $value) {
		  if ($_FILES[$key]["error"] == 0) {
			 // get the name of the file uploaded
			 $fileName = $_FILES[$key]["name"];
	
			 // if the file is not a zip file, then continue to the next file
			 if( strpos($fileName, ".zip") == -1 || strpos($fileName, ".zip") == "" || strpos($fileName, ".zip") == NULL ) {
				continue;
			 }
	
			 $destFolder = kan_fix_path("../assets/themes/");
	
			 $destZipFile = $destFolder . $_FILES[$key]["name"];
	
			 // move the file to the CSS folder
			 move_uploaded_file($_FILES[$key]["tmp_name"], $destZipFile );
	
			 // create object
			 $zip = new ZipArchive() ;
	
			 // open archive
			 if ($zip->open( $destZipFile ) !== TRUE) {
				die ('Could not open archive');
			 } else {
			
			    $index = $zip->locateName("data.json",ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR);
				$data = $zip->getFromIndex($index);
				
				$records = json_decode($data);
				
				//print_r($records);
				
				if( $records !== NULL ) {
					$theme_data = $records->{'theme_data'};
					
                    $count = $this->Theme->count(array(
                        'filter' => array('ThemeName' => $theme_data->{'ThemeName'})
                    ));
					
					// if no data was returned, then insert the component
					if( $count == 0 ) {
						
                        $theme = new Theme(array(
                            'ThemeName' => $theme_data->{'ThemeName'},
                            'ThemeDesc' => $theme_data->{'ThemeDesc'},
                            'ThemeFolder' => $theme_data->{'ThemeFolder'},
                            'ThemePreview' => $theme_data->{'ThemePreview'},
                            'DateAdded' => date('Y-m-d')
                        ));
                        $theme->save();
                        
						// populate the stylesheets
						$stylesheets = $records->{'stylesheets'};
						//$insertSQL = "INSERT INTO site_themes_css (ThemeID,CSSName,CSSDescription,CSSFolder,CSSURL,DateAdded)  VALUES (%s,%s,%s,%s,%s,now()) ";
						
						if( is_array($stylesheets) ) {
							
							for($i = 0; $i <  count($stylesheets); $i++ ) {
								$stylesheet = $stylesheets[$i];
								$themeCSS = new ThemeCSS(array(
                                    'ThemeID' => $theme->getId(),
                                    'CSSName' => $stylesheet->{'CSSName'},
                                    'CSSDescription' => $stylesheet->{'CSSDescription'},
                                    'CSSFolder' => $stylesheet->{'CSSFolder'},
                                    'CSSURL' => $stylesheet->{'CSSURL'}
                                ));
                                $themeCSS->save();
							}
						} else {
                            
                            $themeCSS = new ThemeCSS(array(
                                'ThemeID' => $theme->getId(),
                                'CSSName' => $stylesheets->{'CSSName'},
                                'CSSDescription' => $stylesheets->{'CSSDescription'},
                                'CSSFolder' => $stylesheets->{'CSSFolder'},
                                'CSSURL' => $stylesheets->{'CSSURL'}
                            ));
                            $themeCSS->save();
						}
						
						// extract contents to destination directory
				 		@$zip->extractTo($destFolder);
						
					} else {
						echo "<b>" . $theme->getData('ThemeName') . " Theme</b> Is Already Present In This KAN Installation.<br />";	
					}
					
				} else {
					die("Invalid KAN Archive Uploaded. Please check and re-upload");
				}
			 }
	
			 // close archive
			 $zip->close();
	
			 // delete zip file
			 @unlink( $destZipFile );
		  }
	   }
	}
	
	
	public function createTheme() {
		global $fileUtils;
		
		if( !defined("IN_CMS") || !IN_CMS ) {
            trigger_error("This function should only be run from the CMS interface");
            return;
        }
		
		$folderPath = kan_fix_path($_POST['ThemeFolder']);
		
		/*if( !is_dir($folderPath) ) {
			echo("Invalid Theme Folder Specified: <b>$folderPath</b> " );
			return false;
		}*/
		
		// create the folder and do not report if it exists or not
		if( !@mkdir($folderPath) ) {
			echo "<div class='cms-warning'>Failed To Create The Theme Folder: <b>$folderPath</b>. <br />Please check permissions of the <b>../assets/themes/</b> directory or if $folderPath already exists. </div>";
			return false;
		}
		
		// copy the contents of the temp theme folder to the new specified folder
		$fm = new FileManager();
		$fm->smartCopy( kan_fix_path('../cms/utils/temp_theme/'), $folderPath );
		
		// check to ensure the theme information was copied successfully, 
		// before attempting the insert of the data
	
		$theme = new Theme( array(
			"ThemeName" => $_POST['ThemeName'],
			"ThemeDesc" => $_POST['ThemeDesc'],
			"ThemeFolder" => $_POST['ThemeFolder'],
			"ThemePreview" => $_POST['ThemePreview'],
			"DateAdded" => date("Y-m-d")
		));
		$theme->save();
		
		$theme_css = new ThemeCSS( array(
			"ThemeID" => $theme->getId(),
			"CSSName" => "Default Theme CSS",
			"CSSDescription" => "Default Theme Stylesheet Which is included by default",
			"CSSFolder" =>  $_POST['ThemeFolder'] . 'css/default/',
			"CSSURL" => $_POST['ThemeFolder'] . 'css/default/default.css',
			"DateAdded" => date("Y-m-d")
		));
		
		$theme_css->save();
		
		// return true to indicate that the process completed successfully
		return $theme;
	}
	
	public function updateTheme() {
		
		if( !defined("IN_CMS") || !IN_CMS ) {
            trigger_error("This function should only be run from the CMS interface");
            return;
        }
		
		$theme = new Theme( array(
			"id" => $_POST['id'],
			"ThemeName" => $_POST['ThemeName'],
			"ThemeDesc" => $_POST['ThemeDesc'],
			"ThemeFolder" => $_POST['ThemeFolder'],
			"ThemePreview" => $_POST['ThemePreview'],
			"DateAdded" => date("Y-m-d")
		));
		$theme->save();
		
		// return theme object after it has been processed
		return $theme;
	}
    
    /**
     * Duplicates the records and files for a theme
     * 
     * @param int $id
     * @return Theme 
     */
    public function duplicateTheme($id) {
        if( !defined("IN_CMS") || !IN_CMS ) {
            trigger_error("This function should only be run from the CMS interface");
            return;
        }
        
        if( is_int($id) || intval($id) > 0 ) {
			$theme = new Theme($id);
            $theme->setData( array(
                'id' => NULL,
                "ThemeName" => $theme->getData("ThemeName") . " (Copy)"
            ));
			$theme->save();
            
            return $theme;
		}
    }
	
	public function deleteTheme($id) {
		
		if( is_int($id) || intval($id) > 0 ) {
			$theme = new Theme($id);
			$theme->delete();
		}
	}
	
	public function deleteThemes($ids) {
		if( !defined("IN_CMS") || !IN_CMS ) {
            trigger_error("This function should only be run from the CMS interface");
            return;
        }
		
		if( !is_array($ids) ) {
			trigger_error("An array of IDs must be supplied");
			return;
		}
		
		$themes = $this->Theme->find( array(
			'filter' => array('id IN' => $ids)
		));
		
		foreach($themes as $theme) {
			$theme->deleteFiles();	
		}
		
		$this->deleteItems($ids);
	}
}



?>